package Presentacion;

import Clases.Deduccion;
import Clases.Empleado;
import Clases.InfoReporteEmpleado;
import Clases.Pago;
import Clases.crearPDF;
import Control.ControlEmpleado;
import Control.ControlPago;
import Gestor.GestorDeduccion;
import com.csvreader.CsvWriter;
import de.javasoft.plaf.synthetica.SyntheticaLookAndFeel;
import java.io.File;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class OpcionesReportesPlanillaGeneral extends javax.swing.JFrame {

    private static OpcionesReportesPlanillaGeneral instancia = null;
    static ButtonGroup grupo = new ButtonGroup();
    DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
    
    private ImageIcon iconoError;
    private File archivo = null;

    public OpcionesReportesPlanillaGeneral() {
        initComponents();
        grupo.add(jRadioButtonExcel);
        grupo.add(jRadioButtonPDF);
        jRadioButtonExcel.setSelected(true);
    }

    public static OpcionesReportesPlanillaGeneral obtenerInstancia() {
        if (instancia == null) {
            instancia = new OpcionesReportesPlanillaGeneral();
        }
        return instancia;
    }

    public void init() {
        setTitle("Reporte de General Planilla de los Empleados");
        setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
        SwingUtilities.updateComponentTreeUI(this);
        try {
            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        inicioTooltops();
        this.limpiar();
        this.setVisible(true);
    }

    private void inicioTooltops() {
        iconoError = new ImageIcon(getClass().getResource("/Imagenes/warning.png"));

        jLabelRuta.setIcon(iconoError);
        jLabelRuta.setToolTipText("Debe seleccionar una ruta para guardar el archivo.");

        ocultarLabels();
    }

    private void ocultarLabels() {
        jLabelRuta.setVisible(false);
    }

    public void limpiar() {
        labelRuta.setText("");
        archivo = null;
        ocultarLabels();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jRadioButtonExcel = new javax.swing.JRadioButton();
        jRadioButtonPDF = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        labelRuta = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabelRuta = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(396, 390));
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setMinimumSize(new java.awt.Dimension(396, 259));
        jPanel1.setPreferredSize(new java.awt.Dimension(396, 259));

        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton8.setText("Buscar Ruta");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jRadioButtonExcel.setText("Excel (.csv)");
        jRadioButtonExcel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonExcelActionPerformed(evt);
            }
        });

        jRadioButtonPDF.setText("PDF (.pdf)");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel3.setText("Formato del reporte:");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel6.setText("Rutal del archivo:");

        jButton2.setText("Crear");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabelRuta.setText("x");
        jLabelRuta.setMaximumSize(new java.awt.Dimension(24, 24));
        jLabelRuta.setMinimumSize(new java.awt.Dimension(22, 22));
        jLabelRuta.setPreferredSize(new java.awt.Dimension(22, 22));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabelRuta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(labelRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(jButton8))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(18, 18, 18)
                                    .addComponent(jButton1))))
                        .addGap(38, 38, 38))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jRadioButtonExcel)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton2)
                            .addComponent(jRadioButtonPDF)))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelRuta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton8)
                    .addComponent(labelRuta, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE))
                .addGap(26, 26, 26)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jRadioButtonExcel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jRadioButtonPDF)
                .addGap(9, 9, 9)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        //generarReporteGeneralPlanilla();
        if (validarReporte()) {
            if (jRadioButtonExcel.isSelected()) {
                generarReportePlanillaEmpleado(1);
            } else {
                generarReportePlanillaEmpleado(2);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jRadioButtonExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonExcelActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jRadioButtonExcelActionPerformed

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            archivo = fc.getSelectedFile();
            if (archivo.isDirectory()) {
                labelRuta.setText(archivo.toString() + File.separator);
            }
        }
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.limpiar();
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private boolean validarReporte() {
        ocultarLabels();
        boolean itsOk = true;
        if (labelRuta.getText().isEmpty()) {
            jLabelRuta.setVisible(true);
            itsOk = false;
        }

        return itsOk;
    }

    private boolean generarReportePlanillaEmpleado(int opc) {

        //INFORMACION GENERAL NECESARIA
        Date fecha = new Date();
        String fechaString = dateFormat.format(fecha);
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Elegir Destino");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
//**
        ControlEmpleado controlEmpleado = ControlEmpleado.obtenerInstancia();
        ArrayList<Empleado> empleados = controlEmpleado.obtenerListaEmpleados();
        //Empleado empleado = controlEmpleado.getEmpleadoCedula(cedula);
        ControlPago controlPago = ControlPago.obtenerInstancia();
        ArrayList<Date> pago = controlPago.getPago();
        java.sql.Date sqlDate1 = new java.sql.Date((pago.get(0)).getTime());
        java.sql.Date sqlDate2 = new java.sql.Date((pago.get(1)).getTime());

      /*  Double porcentajeDeduccion = 9.17;
        ArrayList<Deduccion> deducciones = GestorDeduccion.obtenerInstancia().getListaDeduccionsActuales();
        for (Deduccion deduccionTemp : deducciones) {
            String nombre = deduccionTemp.getNombre();
            nombre = nombre.toLowerCase().trim();
            if (nombre.contains("ccss") || nombre.contains("c.c.s.s") || nombre.contains("c.c.s.s.") || nombre.contains("caja costarricense del seguro social")) {
                porcentajeDeduccion = deduccionTemp.getPorcentaje();
                //TODO porcentaje de las deduccion 
            }
        }*/
        ArrayList<InfoReporteEmpleado> reportesCompletos = new ArrayList<>();
        //INFORMACION ESPECIFICA POR EMPLEADO
        for (Empleado empleadoTemp : empleados) {
            InfoReporteEmpleado reporte = new InfoReporteEmpleado();
            Pago pagoActual = controlPago.getPagoActual(empleadoTemp.getNumEmpleado(), sqlDate1, sqlDate2);
            reporte.setCodigo(empleadoTemp.getCodigo().toString());//("Codigo");//1
            reporte.setNombre(empleadoTemp.getNombre().toString() + " " + empleadoTemp.getApellido1().toString());//("Nombre");//2
            reporte.setSalario(String.valueOf(pagoActual.getSalarioBase()));//("Salario");//3
            Integer horasExtrasInt = controlPago.getCantHorasExtras(empleadoTemp.getNumEmpleado(), sqlDate1, sqlDate2);
            Integer horasExtra = horasExtrasInt > 0 ? horasExtrasInt / 60 : horasExtrasInt;
            Long horasExtras = Long.valueOf(horasExtra);
            reporte.setHorasTrabajadas(String.valueOf(pagoActual.getCantHorasTrabajadas() - horasExtra));//("Horas");//4
            reporte.setValorHotrasTrabajadas(String.valueOf(pagoActual.getSalarioBase2()));//("Monto");//5
            reporte.setHorasExtras(String.valueOf(horasExtras));//("Extras");//6
            reporte.setValorHorasExtras(String.valueOf(pagoActual.getExtras()));//("Monto");//7
            reporte.setValorHorasYExtras(String.valueOf(pagoActual.getExtras() + pagoActual.getSalarioBase2()));//8 ("Total");//8
            reporte.setPrestamos(String.valueOf(pagoActual.getPrestamos()));//("Prestamos")//9
            reporte.setValorDeducciones(String.valueOf(pagoActual.getDeducciones()));//("Total Deducciones");//10
           // reporte.setValorCCSS(String.valueOf((pagoActual.getSalarioBase() * porcentajeDeduccion) / 100));//("C.C.S.S");//11
            reporte.setValorBonos(String.valueOf(pagoActual.getSumaBonos()));//("Bonos");//12
            reporte.setValorSalarioNeto(String.valueOf(pagoActual.getSalarioNeto()));//("Salario Neto");//13
            reporte.setMetodoPago(empleadoTemp.getOpcionPago());//("Metodo de Pago");//14
            reportesCompletos.add(reporte);
        }

        //INFORMACION EXPORTADA
        if (!reportesCompletos.isEmpty()) {
            if (opc == 1) {
                String ruta = labelRuta.getText() + fechaString + "_reporteGeneralEmpleados" + ".csv";
                boolean existe = new File(ruta).exists();
                if (existe) {
                    File ficheroUsuarios = new File(ruta);
                    ficheroUsuarios.delete();
                }
                try {
                    CsvWriter writer = new CsvWriter(new FileWriter(ruta, true), ';');
                    writer.write("Codigo");//1
                    writer.write("Nombre");//2
                    writer.write("Salario");//3
                    writer.write("Horas");//4
                    writer.write("Monto");//5
                    writer.write("Extras");//6
                    writer.write("Monto");//7
                    writer.write("Total");//8
                    writer.write("Total Préstamos");//9
                    writer.write("Total Deducciones");//10
                    //writer.write("C.C.S.S");//11
                    writer.write("Bonos");//12
                    writer.write("Salario Neto");//13
                    writer.write("Metodo de Pago");//14
                    writer.endRecord();
                    for (InfoReporteEmpleado reportetemp : reportesCompletos) {
                        writer.write(reportetemp.getCodigo());//1
                        writer.write(reportetemp.getNombre());//2
                        writer.write(reportetemp.getSalario());//3
                        writer.write(reportetemp.getHorasTrabajadas());//4
                        writer.write(reportetemp.getValorHotrasTrabajadas());//5
                        writer.write(reportetemp.getHorasExtras());//6
                        writer.write(reportetemp.getValorHorasExtras());//7
                        writer.write(reportetemp.getValorHorasYExtras());//8
                        writer.write(reportetemp.getPrestamos());//9
                        writer.write(reportetemp.getValorDeducciones());//10
                      //  writer.write(reportetemp.getValorCCSS());//11
                        writer.write(reportetemp.getValorBonos());//12
                        writer.write(reportetemp.getValorSalarioNeto());//13
                        writer.write(reportetemp.getMetodoPago());//14
                        writer.endRecord();
                    }
                    writer.close();
                    JOptionPane.showMessageDialog(null, "CSV generado el " + fechaString + " con la información General de Planilla", "Mensaje", JOptionPane.INFORMATION_MESSAGE);

                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    System.out.println(e.getCause());
                }
            } else {
                crearPDF pdf = new crearPDF();
                ArrayList<String> contenidoPDF = new ArrayList<String>();
                //File directorio = chooser.getSelectedFile();
                String ruta = archivo.getPath();
                contenidoPDF.add(" ");
                contenidoPDF.add(" ");
                contenidoPDF.add("Fecha de Reporte: " + fechaString);
                contenidoPDF.add("----------------------------------------------------------------");
                for (InfoReporteEmpleado reportetemp : reportesCompletos) {
                    contenidoPDF.add(" ");
                    contenidoPDF.add(" ");
                    contenidoPDF.add("Código de Empleado: " + reportetemp.getCodigo());//1
                    contenidoPDF.add("Nombre de Empleado: " + reportetemp.getNombre());//2
                    contenidoPDF.add("Salario Base Quincenal: " + reportetemp.getSalario());//3
                    contenidoPDF.add("Horas laboradas por el empleado: " + reportetemp.getHorasTrabajadas());//4
                    contenidoPDF.add("Monto correspondiente a las horas laboradas: " + reportetemp.getValorHotrasTrabajadas());//5
                    contenidoPDF.add("Horas extras laboradas: " + reportetemp.getHorasExtras());//6
                    contenidoPDF.add("Monto correspondiente a las extras laboradas: " + reportetemp.getValorHorasExtras());//7
                    contenidoPDF.add("Total de monto correspondiente al tiempo laborado: " + reportetemp.getValorHorasYExtras());//8
                    contenidoPDF.add("Monto total correspondiente a los préstamos: " + reportetemp.getPrestamos());//9
                    contenidoPDF.add("Monto total correspondiente a las deducciones :" + reportetemp.getValorDeducciones());//10
                    //contenidoPDF.add("Monto correspondiente a la C.C.S.S. :" + reportetemp.getValorCCSS());//11
                    contenidoPDF.add("Monto total correspondiente a los bonos: " + reportetemp.getValorBonos());//12
                    contenidoPDF.add("Salario Neto: " + reportetemp.getValorSalarioNeto());//13
                    contenidoPDF.add("Método de Pago :" + reportetemp.getMetodoPago());//14
                }
                contenidoPDF.add(" ");
                pdf.crearPDF(fechaString, "reporteGeneralEmpleados", contenidoPDF, ruta);
                JOptionPane.showMessageDialog(null, "PDF generado el " + fechaString + " con la información General de Planilla", "Mensaje", JOptionPane.INFORMATION_MESSAGE);

            }
            return true;
        }
        return true;
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OpcionesReportesPlanillaGeneral.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OpcionesReportesPlanillaGeneral.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OpcionesReportesPlanillaGeneral.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OpcionesReportesPlanillaGeneral.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OpcionesReportesPlanillaGeneral().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton8;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelRuta;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButtonExcel;
    private javax.swing.JRadioButton jRadioButtonPDF;
    private javax.swing.JLabel labelRuta;
    // End of variables declaration//GEN-END:variables
}
